<?php

namespace app\api\controller;

use app\common\CacheKey;
use app\common\Jwt;
use think\Response;
use think\facade\Lang;
use think\Controller;
use app\common\Status;

class Base extends Controller
{
    protected $action = '';
    protected $uid = '';
    protected $name = '';
    protected $domain = '';
    protected $header = '';
    protected $lang_type = 0;

    //不需要验证token的接口(注意:获取方法接口名是小写，没有驼峰)
    protected $not_check_token = [
//        'login',
        'dinosaurbazaar',
        'leaderboard',
        'buysuccess',
        'mydinosaur',
        'buydinosaur',
    ];

    public function __construct()
    {
        parent::__construct();
        $this->domain = $this->request->domain();
        $this->header = $header_data = Request()->header();
        $ip = $this->request->ip();
        if ($ip == '0.0.0.0') {
            $this->sendError(array('code' => Status::SYSTEM_ERROR));
        }
        $header_data['accept-language'] = isset($header_data['accept-language']) ? $header_data['accept-language'] : 0;
        //加载语言包
        if ($header_data['accept-language'] == 1) {
            Lang::load(APP_PATH . 'lang/en-us.php');
            $this->lang_type = 1;
        } else if ($header_data['accept-language'] == 0) {
            Lang::load(APP_PATH . 'lang/zh-cn.php');
            $this->lang_type = 0;
        } else {
            Lang::load(APP_PATH . 'lang/zh-cn.php');
            $this->lang_type = 0;
        }
        $this->action = strtolower(Request()->action());

        //验证token
        if (!in_array($this->action, $this->not_check_token)) {
            $token = isset($header_data['authorization']) ? $header_data['authorization'] : input('param.authorization');
            $userAddress = isset($header_data['useraddress']) ? $header_data['useraddress'] : input('param.useraddress');
//            $token_res = $this->checkToken(trim($token), $userAddress);
//            if (!$token_res) {
//                $this->sendError(array('code' => Status::NOT_TOKEN, 'msg' => Lang::get('not_token')));
//            }
        }
    }

    /**
     * @Title: checkToken
     * @Describe
     * @param $token
     * @param $userAddress
     * @return bool
     * @author lijunwei
     * @Date 2021/12/10 14:24
     */
    protected function checkToken($token, $userAddress)
    {
        // $ethereum_url = config('app.ethereum_url');
        // $url = $ethereum_url . 'api/user';
        // $header = array(
        //     'Accept: application/json',
        //     'apiKey: ' . config('app.apiKey'),
        // );
        // $params = ['userAddress' => $userAddress];
        // $info = httpUrl($url, $params, $header );
        // $info = json_decode($info, true);
        // if ($info  == null) {
        //     $this->sendError(array('code' => Status::NOT_TOKEN, 'msg' => Lang::get('not_user')));
        // }
        // // 验证传过来的token和真正返回的token是否一致
        // if ($info['token'] != $token) {
        //     $this->sendError(array('code' => Status::NOT_TOKEN, 'msg' => Lang::get('not_token')));
        // }
        return true;
    }

    /**
     * 操作错误跳转的快捷方法
     * @param string $msg
     * @param string $data
     * @param array $header
     */
    protected function sendError($msg = '', $data = '', array $header = [])
    {
        $code = Status::SYSTEM_ERROR;
        if (is_array($msg)) {
            $code = $msg['code'];
            $msg = $msg['msg'];
        }
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
        $header['Access-Control-Allow-Origin'] = "*";
        $header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type,Device-Type,Token';
        $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
        $header['Access-Control-Allow-Credentials'] = 'true';
        $response = Response::create($result, 'json')->header($header);
        $response->send();
        die();
    }

    function sheli_cc()
    {
        //代理IP直接退出
        if (empty($_SERVER['HTTP_VIA'])) {
            return false;
        }
        //防止快速刷新
        session_start();
        $seconds = '60'; //时间段[秒]
        $refresh = '12'; //刷新次数
        //设置监控变量
        $cur_time = time();
        if (isset($_SESSION['last_time'])) {
            $_SESSION['refresh_times'] += 1;
        } else {
            $_SESSION['refresh_times'] = 1;
            $_SESSION['last_time'] = $cur_time;
        }
        //处理监控结果
        if ($cur_time - $_SESSION['last_time'] < $seconds) {
            if ($_SESSION['refresh_times'] >= $refresh) {
                return false;
            }
        } else {
            $_SESSION['refresh_times'] = 0;
            $_SESSION['last_time'] = $cur_time;
            return true;
        }
    }

    // 根据ip获取地址信息
    public function ipForCountry($ip)
    {
        $ip2region = new \Ip2Region();
        $info = $ip2region->btreeSearch($ip);
        $info = explode('|', $info['region']);
        return [
            'country' => $info[0] ?? '',
            'province' => $info[2] ?? '',
            'city' => $info[3] ?? '',
        ];
    }

    /**
     * 验证参数
     * @access protected
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array $message 提示信息
     */
    protected function check(array $data, $validate, array $message = [])
    {
        $validateResult = $this->validate($data, $validate, $message);
        if ($validateResult !== true) {
            if (!$validateResult) {
                $validateResult = 'param_err';
            }
            //动态返回错误参数名，对应的状态码
            if (strpos($validateResult, ':') !== false) {
                $validateResult = explode(':', $validateResult);
                ResponseDirect(lang($validateResult[0]), (int)$validateResult[1]);
            }
            ResponseDirect($validateResult, Status::ARGS_ERROR);
        }
    }
}
